package com.sakura.service.impl;

import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakura.constant.PageConstant;
import com.sakura.constant.StatusConstant;
import com.sakura.dto.QueryCheckRecordDTO;
import com.sakura.dto.UpdateCheckRecordDTO;
import com.sakura.entity.CheckProject;
import com.sakura.entity.CheckRecord;
import com.sakura.entity.Elderly;
import com.sakura.entity.Manager;
import com.sakura.service.CheckProjectService;
import com.sakura.service.CheckRecordService;
import com.sakura.mapper.CheckRecordMapper;
import com.sakura.service.ElderlyService;
import com.sakura.service.ManagerService;
import com.sakura.util.EntityConverter;
import com.sakura.util.R;
import com.sakura.vo.CheckRecordDetailVO;
import com.sakura.vo.QueryCheckRecordVO;
import com.sakura.vo.UnCheckProjectRecordVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Sakura
 * @description 针对表【check_record】的数据库操作Service实现
 * @createDate 2023-11-22 15:49:03
 */
@Service
public class CheckRecordServiceImpl extends ServiceImpl<CheckRecordMapper, CheckRecord>
        implements CheckRecordService {

    @Autowired
    private ElderlyService elderlyService;

    @Autowired
    private CheckProjectService checkProjectService;

    @Autowired
    private ManagerService managerService;

    /**
     * 未完成的计划
     *
     * @param elderlyId:
     * @return List<UnCheckProjectRecordVO>
     * @author Sakura
     * @date 2023/12/20 17:10
     */
    @Override
    public List<UnCheckProjectRecordVO> getByElderlyId(Long elderlyId) {
        List<UnCheckProjectRecordVO> unCheckProjectRecordVOS = getUnCheckProjectRecordVOS(elderlyId);
        List<UnCheckProjectRecordVO> unFinishedList = unCheckProjectRecordVOS.stream().filter(item -> item.getFinished() == 0).collect(Collectors.toList());
        return unFinishedList;
    }

    /**
     * 查询当天未完成检查的记录
     *
     * @param elderlyId:
     * @return List<UnCheckProjectRecordVO>
     * @author Sakura
     * @date 2023/12/21 10:55
     */
    private List<UnCheckProjectRecordVO> getUnCheckProjectRecordVOS(Long elderlyId) {
        LambdaQueryWrapper<CheckRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(CheckRecord::getElderlyId, elderlyId);

        //只查找今天范围内的老人
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = LocalDateTime.of(today, LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(today, LocalTime.MAX);
        recordWrapper.between(CheckRecord::getCreateTime, startOfDay, endOfDay);

        List<CheckRecord> recordList = this.list(recordWrapper);
        List<UnCheckProjectRecordVO> unCheckProjectRecordVOS = getUnCheckProjectRecordVOS(elderlyId, recordList);
        return unCheckProjectRecordVOS;
    }

    /**
     * 处理查询后的数据
     *
     * @param elderlyId:
     * @param recordList:
     * @return List<UnCheckProjectRecordVO>
     * @author Sakura
     * @date 2023/12/21 10:55
     */
    private List<UnCheckProjectRecordVO> getUnCheckProjectRecordVOS(Long elderlyId, List<CheckRecord> recordList) {
        Elderly elderly = elderlyService.getById(elderlyId);
        ///查出老人今天所有的活动然后转换类型为VO对象
        List<UnCheckProjectRecordVO> unCheckProjectRecordVOS = recordList.stream().map(item -> {
            UnCheckProjectRecordVO unCheckProjectRecordVO =
                    EntityConverter.copyAndGetSingle(item, UnCheckProjectRecordVO.class);
            CheckProject project = checkProjectService.getById(item.getProjectId());
            //老人的姓名 和项目的名称
            unCheckProjectRecordVO
                    .setName(elderly.getName())
                    .setProjectName(project.getName())
                    .setElderlyId(elderlyId)
                    .setMin(project.getMin())
                    .setMax(project.getMax());
            Long checkUserId = item.getCheckUser();
            if (checkUserId != null) {
                Manager manager = managerService.getById(checkUserId);
                if (manager != null) {
                    unCheckProjectRecordVO.setCheckUserName(manager.getName());
                    unCheckProjectRecordVO.setCheckUserPhone(manager.getPhone());
                }
            }
            return unCheckProjectRecordVO;
        }).collect(Collectors.toList());
        return unCheckProjectRecordVOS;
    }

    /**
     * 已完成的记录
     *
     * @param elderlyId :
     * @param pageNo
     * @return List<UnCheckProjectRecordVO>
     * @author Sakura
     * @date 2023/12/20 17:10
     */
    @Override
    public List<UnCheckProjectRecordVO> getFinishedByElderlyId(Long elderlyId, Integer pageNo) {
        //我是查找所有记录
        LambdaQueryWrapper<CheckRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(CheckRecord::getElderlyId, elderlyId);
        recordWrapper.orderByDesc(CheckRecord::getCreateTime);
        if (pageNo == null || pageNo <= 0) {
            pageNo = 1;
        }
        List<CheckRecord> recordList = this.list(recordWrapper);
        List<UnCheckProjectRecordVO> unCheckProjectRecordVOS = getUnCheckProjectRecordVOS(elderlyId, recordList);
        int start = (pageNo - 1) * PageConstant.PAGE_SIZE;
        //本来是没有分页的，我们自定义分页
        List<UnCheckProjectRecordVO> finishedList = unCheckProjectRecordVOS.stream()
                //这里时间过滤注意一下,我们只过滤今天范围之前的,不包括今天,所以这么些没问题
                .filter(item -> new Date().after(item.getCreateTime()))
                .skip(start)
                .limit(PageConstant.PAGE_SIZE)
                .collect(Collectors.toList());
        return finishedList;
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.stream().skip(0).limit(2).forEach(item -> System.out.println(item));
    }

    /**
     * 网格员查询需要检查的项目
     *
     * @param gridId:
     * @param pageNo:
     * @return Map<String, Object>
     * @description 网格员查询需要检查的项目
     * @createTime 2023/12/21 11:02
     */
    @Override
    public Map<String, Object> getNeedCheckProject(Long gridId, Integer pageNo) {
        //返回结果对象
        Map<String, Object> map = new HashMap<>();

        if (pageNo == null || pageNo <= 0) {
            pageNo = 1;
        }

        AtomicInteger unFinishedNum = new AtomicInteger();
        AtomicInteger finishedNum = new AtomicInteger();

        //先去找出该网格员管理哪些老人
        LambdaQueryWrapper<Elderly> elderlyWrapper = new LambdaQueryWrapper<>();
        elderlyWrapper.eq(Elderly::getGridId, gridId);
        List<Elderly> elderlyList = elderlyService.list(elderlyWrapper);
        List<Long> elderlyIds = elderlyList.stream().map(item -> item.getId()).collect(Collectors.toList());

        //不为空则查询
        LambdaQueryWrapper<CheckRecord> recordWrapper = new LambdaQueryWrapper<>();
        //只查询自己管理的老人
        recordWrapper.in(elderlyIds.size() > 0, CheckRecord::getElderlyId, elderlyIds);
        //只查找今天范围内的老人
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = LocalDateTime.of(today, LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(today, LocalTime.MAX);
        recordWrapper.between(CheckRecord::getCreateTime, startOfDay, endOfDay);
        //分页
        Page<CheckRecord> recordPage = this.page(new Page<>(pageNo, PageConstant.PAGE_SIZE), recordWrapper);
        List<UnCheckProjectRecordVO> unCheckProjectRecordVOS = recordPage.getRecords().stream().map(item -> {
            Elderly elderly = elderlyService.getById(item.getElderlyId());
            UnCheckProjectRecordVO unCheckProjectRecordVO =
                    EntityConverter.copyAndGetSingle(item, UnCheckProjectRecordVO.class);
            CheckProject project = checkProjectService.getById(item.getProjectId());
            //老人的姓名 和项目的名称
            unCheckProjectRecordVO
                    .setName(elderly.getName())
                    .setProjectName(project.getName())
                    .setElderlyId(item.getElderlyId())
                    .setMin(project.getMin())
                    .setImage(project.getImage())
                    .setMax(project.getMax());
            return unCheckProjectRecordVO;
        }).collect(Collectors.toList());

//        统计所有任务的完成情况
        List<CheckRecord> list = this.list(recordWrapper);
        list.stream().forEach(item -> {
            if (item.getFinished() != null) {
                if (item.getFinished() == StatusConstant.UN_FINISHED) {
                    unFinishedNum.getAndIncrement();

                } else if (item.getFinished() == StatusConstant.FINISHED) {
                    finishedNum.getAndIncrement();
                }
            }
        });

        map.put("list", unCheckProjectRecordVOS);
        map.put("unFinishedNum", unFinishedNum.get());
        map.put("finishedNum", finishedNum.get());
        return map;
    }

    /**
     * 根据id查询检查记录详情
     *
     * @param recordId:
     * @return R
     * @author Sakura
     * @date 2023/12/26 14:05
     */
    @Override
    public R getCheckRecordDetailById(Long recordId) {
        CheckRecord checkRecord = this.getById(recordId);
        if (checkRecord != null) {
            CheckProject checkProject = checkProjectService.getById(checkRecord.getProjectId());
            //基本信息拷贝
            CheckRecordDetailVO checkRecordDetailVO = EntityConverter.copyAndGetSingle(checkRecord, CheckRecordDetailVO.class);

            //老人信息拷贝
            Elderly elderly = elderlyService.getById(checkRecord.getElderlyId());
            if (elderly != null) {
                checkRecordDetailVO.setElderlyName(elderly.getName());
                checkRecordDetailVO.setElderlyPhone(elderly.getPhone());
                checkRecordDetailVO.setElderlyRoomNumber(elderly.getRoomNumber());
                //身份证号
                String elderlyIdCard = elderly.getIdCard();
                checkRecordDetailVO.setElderlyAge(IdcardUtil.getAgeByIdCard(elderlyIdCard));

                //性别
                int gender = IdcardUtil.getGenderByIdCard(elderlyIdCard);
                if (gender == 1) {
                    checkRecordDetailVO.setElderlySex("男");
                } else if (gender == 0) {
                    checkRecordDetailVO.setElderlySex("女");
                }
            }

            //项目信息拷贝
            if (checkProject != null) {
                checkRecordDetailVO.setProjectName(checkProject.getName());
                checkRecordDetailVO.setImage(checkProject.getImage());
                checkRecordDetailVO.setMax(checkProject.getMax());
                checkRecordDetailVO.setMin(checkProject.getMin());
                checkRecordDetailVO.setParam(checkRecord.getParam());
                checkRecordDetailVO.setConclusion(checkRecord.getConclusion());
            }
            return R.success(checkRecordDetailVO);
        }
        return R.error("记录不存在");
    }

    /**
     * 记录检查结果
     * @param updateCheckRecordDTO:
     * @return R
     * @author Sakura
     * @date 2023/12/26 14:06
     */
    @Override
    public R updateCheckRecord(UpdateCheckRecordDTO updateCheckRecordDTO) {
        CheckRecord checkRecord = EntityConverter.copyAndGetSingle(updateCheckRecordDTO, CheckRecord.class);
        checkRecord.setCheckTime(new Date());
        checkRecord.setFinished(1);
        boolean result = this.updateById(checkRecord);
        return R.getResult(result);
    }

    @Override
    public R getPage(QueryCheckRecordDTO queryCheckRecordDTO) {
        LambdaQueryWrapper<CheckRecord> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper
                .eq(queryCheckRecordDTO.getId() != null && queryCheckRecordDTO.getId() != 0,
                        CheckRecord::getId, queryCheckRecordDTO.getId()).orderByDesc((CheckRecord::getCreateTime));

        queryWrapper.eq(queryCheckRecordDTO.getGridName() != null && queryCheckRecordDTO.getGridName() != 0,
                CheckRecord::getCheckUser, queryCheckRecordDTO.getGridName());
        //老人姓名查询不为空
        if (queryCheckRecordDTO.getElderlyName() != null && !"".equals(queryCheckRecordDTO.getElderlyName())) {
            LambdaQueryWrapper<Elderly> elderlyQueryWrapper = new LambdaQueryWrapper<>();
            elderlyQueryWrapper.like(Elderly::getName, queryCheckRecordDTO.getElderlyName());
            List<Elderly> elderlyList = elderlyService.list(elderlyQueryWrapper);
            List<Long> elderlyIds = elderlyList.stream().map(item -> item.getId()).collect(Collectors.toList());
            queryWrapper.in(elderlyIds!= null && elderlyIds.size() > 0, CheckRecord::getElderlyId, elderlyIds);

        }
        //项目名称不为空
        if (queryCheckRecordDTO.getProjectName()!= null &&!"".equals(queryCheckRecordDTO.getProjectName())) {
            LambdaQueryWrapper<CheckProject> projectQueryWrapper = new LambdaQueryWrapper<>();
            projectQueryWrapper.like(CheckProject::getName, queryCheckRecordDTO.getProjectName());
            List<CheckProject> projectList = checkProjectService.list(projectQueryWrapper);
            List<Long> projectIds = projectList.stream().map(item -> item.getId()).collect(Collectors.toList());
            queryWrapper.in(projectIds!= null && projectIds.size() > 0, CheckRecord::getProjectId, projectIds);
        }

        //设置查询状态
        queryWrapper.eq(queryCheckRecordDTO.getFinished() != null,
                CheckRecord::getFinished, queryCheckRecordDTO.getFinished());

        Page<CheckRecord> checkRecordPage =
                this.page(new Page<>(queryCheckRecordDTO.getCurrent(), queryCheckRecordDTO.getPageSize()), queryWrapper);

        List<CheckRecord> checkRecords = checkRecordPage.getRecords();

        List<QueryCheckRecordVO> voList = checkRecords.stream().map(item -> {
            QueryCheckRecordVO checkRecordVO = EntityConverter.copyAndGetSingle(item, QueryCheckRecordVO.class);

            //设置管理员信息
            Long checkUser = item.getCheckUser();
            if (checkUser!= null) {
                Manager grid = managerService.getById(checkUser);
                checkRecordVO.setGridName(grid.getName());
                checkRecordVO.setGridPhone(grid.getPhone());
            }
            //设置老人信息
            Elderly elderly = elderlyService.getById(item.getElderlyId());
            if (elderly!= null) {
                checkRecordVO.setElderlyName(elderly.getName());
                checkRecordVO.setElderlyPhone(elderly.getPhone());
            }

            //设置项目信息
            CheckProject checkProject = checkProjectService.getById(item.getProjectId());
            if (checkProject!= null) {
                checkRecordVO.setProjectName(checkProject.getName());
            }

            return checkRecordVO;
        }).collect(Collectors.toList());

        Page<QueryCheckRecordVO> voPage = new Page<>();
        BeanUtils.copyProperties(checkRecordPage, voPage, "records");
        voPage.setRecords(voList);

        return R.success(voPage);
    }

}




